package com.ha7419x.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;

import java.nio.charset.Charset;
import java.util.Base64;

/**
 * 进行授权访问处理
 */
public class AuthorizedRequestFilter extends ZuulFilter {
    @Override
    public String filterType() {
        //zuul过滤执行的位置， pre 之前  route 路由请求  post 路由之后  error 出错
        return "pre";
    }

    @Override
    public int filterOrder() {
        return 0;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Override
    public Object run() {
        //当前请求的上下文
        RequestContext currentContext = RequestContext.getCurrentContext();
        String auth = "admin:123456";
        byte[] bytes = Base64.getEncoder().encode(auth.getBytes(Charset.forName("US-ASCII")));
        //加密的信息 要和 basic 只有有個 空格 不然会报错
        String authHeader = "Basic " + new String(bytes);
        currentContext.addZuulRequestHeader("Authorization", authHeader);
        return null;
    }
}
